//
//  countryAreaListearchViewController.swift
//  funcode
//
//  Created by Wan Jiading on 2016/11/25.
//  Copyright © 2016年 WanJiading. All rights reserved.
//

import UIKit

class CountryAreaViewController: IvyDadBaseViewController, UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate {
	
	/// 选中一项后
	var selectedItem: ((CountryArea) -> ())?
	
	let cellID = "CountryAreaCell"
	var dataList: [CountryAreaList] = [CountryAreaList]()
	var resultDataList: [CountryAreaList]!
//	var dataListForSearch: [CountryArea]?
	
	@IBOutlet weak var searchBar: UISearchBar!
	@IBOutlet weak var tableView: UITableView!
	@IBOutlet weak var resultTableView: UITableView!
	
	@IBOutlet weak var resultTableViewBottom: NSLayoutConstraint!
	
	override func viewDidLoad() {
		super.viewDidLoad()
		
		initData()
		setupSubViews()
		setupNotifications()
	}
	
	func setupSubViews() {
		self.navigationItem.title = "选择国家和地区"
		
		self.resultTableView.isHidden = true
		
		searchBar.placeholder = "搜索国家和地区"
		searchBar.showsCancelButton = false
		searchBar.backgroundImage = UIImage()
		searchBar.backgroundColor = UIColor.rgb("cecece")
		searchBar.tintColor = UIColor.rgb("333333")
		
		// 索引
		tableView.sectionIndexColor = UIColor.rgb("84a740")
		tableView.sectionIndexBackgroundColor = UIColor.clear
		tableView.dataSource = self
		tableView.delegate = self
		
		resultTableView.sectionIndexColor = UIColor.rgb("84a740")
		resultTableView.sectionIndexBackgroundColor = UIColor.clear
		resultTableView.dataSource = self
		resultTableView.delegate = self
		
	}
	
	func setupNotifications() {
		
		SharedNotificationCenter.addObserver(self, selector: #selector(keybaordWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
		SharedNotificationCenter.addObserver(self, selector: #selector(keybaordWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
		
	}
	
	
	func keybaordWillHide(_ note :Notification) {
//		DebugLog(note)
		UIView.animate(withDuration: 0.25, animations: { [unowned self] in
			self.resultTableViewBottom.constant = 0
			self.view.layoutIfNeeded()
//			self.resultTableView.layoutIfNeeded()
		})
	}
	func keybaordWillShow(_ note :Notification) {
//		DebugLog(note)
		let frameEnd = note.userInfo![UIKeyboardFrameEndUserInfoKey] as! CGRect
//		DebugLog("\(frameEnd.size.height)")
		UIView.animate(withDuration: 0.25, animations: { [unowned self] in
			self.resultTableViewBottom.constant = frameEnd.size.height
			self.view.layoutIfNeeded()
//			self.resultTableView.layoutIfNeeded()
		})
	}
	
	func dismissSelf() {
		self.dismiss(animated: true, completion: {
			
		})
	}
	
	// MARK: - UITableViewDataSource
	
	func numberOfSections(in tableView: UITableView) -> Int {
		if self.resultTableView.isHidden {
			return dataList.count
		} else {
			return resultDataList.count
		}
	}
	
	func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
		if self.resultTableView.isHidden {
			return dataList[section].countryAreaList!.count
		} else {
			return resultDataList[section].countryAreaList!.count
		}
	}
	
	func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
		
		let cell = tableView.dequeueReusableCell(withIdentifier: cellID) as! CountryAreaCell
		var countryArea: CountryArea
		if self.resultTableView.isHidden {
			countryArea = dataList[indexPath.section].countryAreaList![indexPath.row]
		} else {
			countryArea = resultDataList[indexPath.section].countryAreaList![indexPath.row]
		}
		cell.countryArea = countryArea
		
		return cell
	}
	
	func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
		return 50
	}
	
	func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
		
		var countryArea: CountryArea
		if self.resultTableView.isHidden {
			countryArea = dataList[indexPath.section].countryAreaList![indexPath.row]
		} else {
			countryArea = resultDataList[indexPath.section].countryAreaList![indexPath.row]
		}
		selectedItem?(countryArea)
		dismissSelf()
	}
	
	// MARK: SectionHeaderTitle
	
	func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
		return 28
	}
	
	func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
		if self.resultTableView.isHidden {
			return dataList[section].letter
		} else {
			return resultDataList[section].letter
		}
	}
	
	// MARK: - 右边的索引
	
	/// 索引显示
	func sectionIndexTitles(for tableView: UITableView) -> [String]? {
		
		var CountryAreaList = [String]()
		
		if self.resultTableView.isHidden {
			for c in dataList {
				CountryAreaList.append(c.letter!)
			}
		} else {
			for c in resultDataList {
				CountryAreaList.append(c.letter!)
			}
		}
		
		return CountryAreaList
	}
	
	/// 索引被点击
	func tableView(_ tableView: UITableView, sectionForSectionIndexTitle title: String, at index: Int) -> Int {
//		DebugLog("\(index)    \(title)")
		
		//		let selectIndexPath = IndexPath(row: 0, section: index)
		//		tableView.scrollToRow(at: selectIndexPath, at: .bottom, animated: true)
		
		return index
	}
	
	
	
	// MARK: - SearchBarDelegate
	
	/// 能否获取焦点
	func searchBarShouldBeginEditing(_ searchBar: UISearchBar) -> Bool {
		DebugLogFunc()
		
		searchBar.setShowsCancelButton(true, animated: true)
		
//		if dataListForSearch == nil {
//			dataListForSearch = [CountryArea]()
//			for item in dataList {
//				dataListForSearch = dataListForSearch! + item.countryAreaList!
//			}
//		}
		
		return true
	}
	
	/// 获得焦点
	func searchBarTextDidBeginEditing(_ searchBar: UISearchBar) {
//		DebugLogFunc()
		
		for view in searchBar.subviews {
//			DebugLog(view)
			for view in view.subviews {
				if view.isKind(of: NSClassFromString("UINavigationButton")!) {
					let cancelBtn = view as! UIButton
					cancelBtn.setTitleColor(UIColor.rgb("333333"), for: .normal)
					cancelBtn.adjustsImageWhenHighlighted = false
				}
			}
		}
		
	}
	
	/// 能否修改
	func searchBar(_ searchBar: UISearchBar, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
//		DebugLogFunc()
		return true
	}
	
	/// 内容发生改变
	func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
//		DebugLog(searchText)
		
		var results = [CountryAreaList]()
		var letterModel: CountryAreaList!
		for item in dataList {
			var countryAreaList = [CountryArea]()
			for c in item.countryAreaList! {
				if c.area_name!.contains(searchText.uppercased()) {
					countryAreaList.append(c)
				}
			}
			if countryAreaList.count > 0 {
				letterModel = CountryAreaList()
				letterModel.letter = item.letter
				letterModel.countryAreaList = countryAreaList
				results.append(letterModel)
			}
		}
		
		self.resultTableView.isHidden = false
		self.resultDataList = results
		self.resultTableView.reloadData()
		self.tableView.isHidden = true
	}
	
	
	func searchBarTextDidEndEditing(_ searchBar: UISearchBar) {
//		DebugLogFunc()
	}
	
	/// 点击 取消 按钮
	func searchBarCancelButtonClicked(_ searchBar: UISearchBar) {
//		DebugLogFunc()
		
		searchBar.setShowsCancelButton(false, animated: true)
		self.searchBar.resignFirstResponder()
		
		self.resultTableView.isHidden = true
		self.tableView.isHidden = false
		
		searchBar.text = ""
	}
	
	/// 点击键盘上的 搜索按钮
	func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
//		DebugLogFunc()
	}
	
	/// 书签按钮
	func searchBarBookmarkButtonClicked(_ searchBar: UISearchBar) {
//		DebugLogFunc()
	}
	
	/// 结果列表
	func searchBarResultsListButtonClicked(_ searchBar: UISearchBar) {
//		DebugLogFunc()
	}
	
	func searchBarShouldEndEditing(_ searchBar: UISearchBar) -> Bool {
//		DebugLogFunc()
		return true
	}
	
	func searchBar(_ searchBar: UISearchBar, selectedScopeButtonIndexDidChange selectedScope: Int) {
//		DebugLogFunc()
	}
	
	
	
	// MARK: - 初始化数据
	
	func initData() {
		
		let filePath = MainBundle.path(forResource: "AreaCodeJsonU8.txt", ofType: nil)
		if filePath != nil && filePath!.count > 0 {
			let url = URL(fileURLWithPath: filePath!)
			if SharedFileManager.fileExists(atPath: filePath!) {
				let jsonData = try! Data.init(contentsOf: url)
				let dict = try! JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableLeaves) as! [String: AnyObject]
				DebugLog(dict)
				let data = dict["data"] as! [String: AnyObject]
				let letterList = data["letter_list"] as! [AnyObject]
				
				for item in letterList {
			
					let letterModel = item as! [String: AnyObject]
					let letter = letterModel["letter"] as! String
					DebugLog("letter = \(letter)")
					let areaModelList = letterModel["area_code_list"] as! [AnyObject]
					
					let countryAreaList = CountryAreaList()
					countryAreaList.letter = letter
					countryAreaList.countryAreaList = [CountryArea]()
					for item in areaModelList {
						let areaModel = item as! [String: String]
						
						let areaCode = areaModel["area_code"]!
						let areaName = areaModel["area_name"]!
//						let areaNameFirstLetter = areaModel["area_name_first_letter"]!
						let areaNameSpell = areaModel["area_name_spell"]!
					
						let countryArea = CountryArea.init(areaCode, areaName, areaNameSpell)
						countryAreaList.countryAreaList?.append(countryArea)
						
					}
					dataList.append(countryAreaList)
				}
			}
		}
		
	}
	
}
